# -- coding: utf-8 --
# 这个模块用于封装英文关键字方法


class Action:

    driver = None

    def open_browser(self, browser):
        """
        打开浏览器，生成浏览器驱动对象
        :param browser: 浏览器名称，是字符串
        :return: None
        """
        from selenium import webdriver
        driver = self.driver   # 属性本地化，可以减少self的使用
        if hasattr(webdriver, browser):
            driver = getattr(webdriver, browser)()
        else:
            driver = webdriver.Firefox()
        driver.implicitly_wait(5)
        driver.maximize_window()
        self.driver = driver

    def open_page(self, url):
        self.driver.get(url)

    def get_element(self, locator):
        """
        用于获取页面元素对象，返回找到的元素对象
        :param locator: 定位器，格式为by=what的字符串
        :return: 元素对象
        """
        by = str(locator).split('=')[0]  # 获取元素定位方式的字符串
        attr = str(locator).split('=')[1]  # 获取元素定位方式对应的属性值
        from selenium.webdriver.common.by import By
        return self.driver.find_element(getattr(By, by), attr)  # 通过反射机制动态地获得元素定位方式对象

    def input(self, locator, value):
        element = self.get_element(locator)
        element.click()
        element.clear()
        element.send_keys(value)

    def click(self, locator):
        element = self.get_element(locator)
        element.click()

    def sleep(self, second):
        import time
        time.sleep(int(second))

    def confirm_alert(self):
        self.driver.switch_to.alert.accept()

    def close_browser(self):
        self.driver.close()
        self.driver = None   # 彻底关闭